<?php

/**
 * Sous-Element de parsing pour les tags de la forme {$...} ou {$$...}
 *
 * @category   McCube
 * @package    Template\Parser\Element
 * @author     Leiha Sellier <leiha.sellier@gmail.com>
 * @license    http://creativecommons.org/licenses/by/3.0/  CC BY 3.0
 * @link       http://code.google.com/p/mechanics-cubes/
 */
class McCube_Template_Parser_Element_Variable_Version1
    extends McCube_Template_Parser_Element_Variable_Abstract{

    /**
     *
     *
     * @param string $variable
     * @param string $inTag
     * @return string
     */
    public function build($variable, $inTag){
        $variable = parent::_parse('\[(.*?)(?<!\\\)]' , '_buildCallbackForArrayIndex', $variable);
        $variable = parent::_parse('\((.*?)(?<!\\\)\)', '_buildCallbackForMethodArg' , $variable);
        $variable = '$'.$variable;

        if($inTag)
            $variable = parent::_applyFilters($variable, $inTag);

        return parent::buildPhpTag($variable);
    }

    /**
     *
     *
     * @param string $variable
     * @param string $inTag
     * @return string
     */
    protected function _buildCallbackForArrayIndex($matches){
        if($matches[1][0] == '$')
            return '['.$matches[1].']';

        $ret = $this->_stripSlashes($matches[1], ']');
        return '[\''.addslashes($ret).'\']';
    }

    /**
     *
     *
     * @param array $matches
     * @return string
     */
    protected function _buildCallbackForMethodArg($matches){
        $args = preg_split('~(?<!\\\),~', $matches[1]);

        foreach($args as &$arg){
            if($arg && $arg[0] != '$')
                $arg = '\''.trim($arg).'\'';
        }
        return '('.implode(', ', $args).')';
    }
}